using BackOffice.Application.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Backoffice.Domain.Repositories;
using Backoffice.Domain.Entities.App;
using Admin2025.Application.DTOs;
using BackOffice.Application.DTOs;

namespace BackOffice.Api.Controllers
{
  [ApiController]
  [Route("api/[controller]")]
  [Authorize]
  public class RoleController : ControllerBase
  {
    private readonly IRoleService _roleService;
    private readonly IRepository<AppRole> _roleRepo;

    public RoleController(IRoleService roleService, IRepository<AppRole> roleRepo)
    {
      _roleService = roleService;
      _roleRepo = roleRepo;
    }
    // 创建角色
    [HttpPost("create")]
    public async Task<IActionResult> Create([FromBody] CreateRoleDto dto)
    {
      var role = await _roleService.CreateRoleAsync(dto);
      return Ok(new { role });
    }
    // 更新角色
    [HttpPut("update/{roleId}")]
    public async Task<IActionResult> Update(Guid roleId, [FromBody] CreateRoleDto dto)
    {
      var result = await _roleService.UpdateRoleAsync(roleId, dto);
      return Ok(result.Data);
    }
    // 删除角色
    [HttpDelete("delete/{roleId}")]
    public async Task<IActionResult> Delete(Guid roleId)
    {
      var result = await _roleService.DeleteRoleAsync(roleId);
      return Ok(result.Data);
    }
    // 分配权限给角色
    [HttpPost("assign-permission/{roleId}")]
    public async Task<IActionResult> AssignPermission(Guid roleId, [FromBody] string permissionCode)
    {
      var result = await _roleService.AssignPermissionToRoleAsync(roleId, permissionCode);
      return Ok(result.Data);
    }
    // 移除角色的权限
    [HttpDelete("remove-permission/{roleId}")]
    public async Task<IActionResult> RemovePermission(Guid roleId, [FromBody] string permissionCode)
    {
      var result = await _roleService.RemovePermissionFromRoleAsync(roleId, permissionCode);
      return Ok(result.Data);
    }
    // 获取角色列表
    [HttpGet("list")]
    public async Task<IActionResult> GetRoles()
    {
      var roles = await _roleRepo.GetAllAsync();
      return Ok(roles);
    }
    // 禁用角色
    [HttpPost("disable/{roleId}")]
    public async Task<IActionResult> Disable(Guid roleId)
    {
      var result = await _roleService.DisableAsync(roleId);
      return Ok(result.Data);
    }
    // 启用角色
    [HttpPost("enable/{roleId}")]
    public async Task<IActionResult> Enable(Guid roleId)
    {
      var result = await _roleService.EnableAsync(roleId);
      return Ok(result.Data);
    }
        // 角色多条件查询
    [HttpPost("search")]
    public async Task<IActionResult> Search([FromBody] RoleSearchDto dto)
    {
      var roles = await _roleService.SearchRolesAsync(dto);
      return Ok(roles.Data);
    }
  }
}
